package dataflowscheme.engine.core;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import dataflowScheme.SynchroPort;

/**
 * Encapsulate data-flow Trigger entity.
 * 
 * @author <a href="mailto:misiak7@gmail.com">Michal Antolik</a>
 *
 */
public class CTrigger implements IConnectableEntity {
	
	/** Data-flow ecore instance of Task */
	private dataflowScheme.Trigger eTrigger;
	
	/** ports of trigger */
	private Set<String> ports = new HashSet<String>();
	
	/** connections leading from Trigger */
	private Map<String, ConnectionAnchor> conns = new HashMap<String, ConnectionAnchor>();

	private final LinkedBlockingQueue<IEvent> eventQueue;
	
	static Logger log = Logger.getLogger(CTrigger.class);
	
	public CTrigger(dataflowScheme.Trigger eTrigger, LinkedBlockingQueue<IEvent> queue) {
		this.eTrigger = eTrigger;
		this.eventQueue = queue;
	}
	
	public void init(){
		for(SynchroPort p : eTrigger.getPorts()){
			ports.add(p.getName());
		}
	}
	
	/**
	 * send signals to start program, new Synchro events are created
	 */
	public void run(){
		for(Map.Entry<String, ConnectionAnchor> entry : conns.entrySet()){

			ConnectionAnchor out = new ConnectionAnchor(this, entry.getKey());
			ConnectionAnchor in = entry.getValue();
			
			try{
				eventQueue.put(new SynchroEvent(out, in));
			}catch(InterruptedException ie){
				log.error("Event parser is dead, can't trigger event from TRIGGER.", ie);
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see dataflowscheme.engine.core.IConnectableEntity#addConnection(String portName, IConnectableEntity oppossiteEntity, String oppossitePortName)
	 */
	public void addConnection(String portName,
			IConnectableEntity oppossiteEntity, String oppossitePortName) {
		if(ports.contains(portName)){
			conns.put(portName, new ConnectionAnchor(oppossiteEntity, oppossitePortName));
		}
	}

	/* (non-Javadoc)
	 * @see dataflowscheme.engine.core.IConnectableEntity#getName()
	 */
	public String getName() {
		return "TRIGGER";
	}

	//NOT implemented methods - not necessary
	
	/* (non-Javadoc)
		 * @see dataflowscheme.engine.core.IConnectableEntity#receiveData(Object data, String portName)
		 */
	public boolean receiveData(Object data, String portName) {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see dataflowscheme.engine.core.IConnectableEntity#receiveResponse(EventMsg event, String portName)
	 */
	public void receiveResponse(EventMsg event, String portName) {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see dataflowscheme.engine.core.IConnectableEntity#receiveSignal(String portName)
	 */
	public boolean receiveSignal(String portName) {
		// TODO Auto-generated method stub
		return false;
	}


}
